package com.winit.iwm.storage.manager;

import com.winit.iwm.storage.dao.UserRepository;
import com.winit.iwm.storage.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by jianke.zhang on 2017/4/20.
 */
@Service
public class UserManagerImpl implements UserManager {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public User findByName(String name) {
        return userRepository.findByName(name);
    }

    @Override
    public Page<User> findByPage(Example<User> example, Pageable pageable) {
        if (null == example) {
            return userRepository.findAll(pageable);
        } else {

        }
        return userRepository.findAll(example, pageable);
    }

    @Override
    public List<User> find(User user) {
        Pattern pattern = Pattern.compile("^" + user.getName() + "$", Pattern.CASE_INSENSITIVE);
        Query query = Query.query(Criteria.where("name").regex(pattern));

        return mongoTemplate.find(query, User.class);
    }

    @Override
    public List<User> findBySubDoc(User user) {
        Query query = Query.query(Criteria.where("address.city").regex("深圳"));

        return mongoTemplate.find(query, User.class);
    }
}
